<?php
/**
 * Created by PhpStorm.
 * User: liuyu
 * Date: 2018/11/19
 * Time: 11:19
 */

namespace app\api\controller\v6;

use app\api\controller\v2\Auth;
use app\common\cachemodel\MapUnlockResult;
use app\common\cachemodel\MonthFortune;
use app\common\cachemodel\YearFortune;
use app\common\lib\PushQueue;
use app\common\lib\Util;
use app\common\model\AppLogicVersion;
use app\common\model\Recode;
use app\common\model\SystemLogicVersion;
use think\Cache;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;
use think\response\Json;
use XznsTools\cache\CacheManage;

/**
 * 运势逻辑更新
 * Class UpdateLogic
 * @package app\api\controller\v6
 */
class UpdateLogic extends Auth
{
    /**
     * 逻辑更新操作,获取更新的数据,加入队列重新计算
     * @return Json
     * @throws \Exception
     */
    public function index(): Json
    {
        if (!request()->isPut())
        {
            return show(config('code.error'), '未知操作');
        }
        $type = input('param.type/d', 0); // 1=》幸运之城，2=》月运，3=》年运
        $rid = input('param.rid/d');// 档案id
        $uid = (int)$this->user['id'];// 当前用户id
        // 参数验证
        if (!$type || !$rid || !$uid)
        {
            return show(config('code.error'), '请稍后重试');
        }
        // 获取当前档案的信息
        $recodeModel = new Recode();
        $recode_info = $recodeModel->getRecode(['uid' => $this->user['id'], 'id' => $rid]);

        if (!$recode_info || $recode_info['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '档案不存在');
        }

        // 获取当前最新版本逻辑信息
        $SystemLogicModel = new SystemLogicVersion();
        $logic_data = $SystemLogicModel->getVersion(['type' => $type]);
        // 获取当前档案逻辑版本号
        $AppLogicModel = new AppLogicVersion();
        $user_logic = $AppLogicModel->getAllVersion(['rid' => $rid, 'type' => $type]);

        // 获取加入队列的数据
        switch (true)
        {
            case $type === 1:
                if (!in_array($logic_data['version'], array_column($user_logic, 'version'), false))
                {
                    Cache::set($uid . ':' . $rid . '_acg_logic_status', 1);
                    //获取用户当前已解锁的数据
                    $unlockIds = (new MapUnlockResult())->getUnlockIdsFromCache(3, $rid);
                    $unlockInfos = (new MapUnlockResult())->batchGetInfoByIds($unlockIds, ['order_id', 'gid']);
                    $max_data = (new \app\common\model\Map())->getNewCityUnlockData($unlockInfos);
                    if ($max_data)
                    {
                        (new PushQueue())->Map($max_data['order_id'], false);
                    }
                }
                break;
            case in_array($type, [2, 3], true):
                $this->fortuneInfo($type, $rid, $logic_data, $user_logic);
                break;
        }
        return show(config('code.success'), '操作成功');
    }

    /**
     * 运势重新计算
     * @param $type
     * @param $rid
     * @param array $logic_data 系统逻辑版本
     * @param array $user_logic 用户已更新的逻辑版本
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function fortuneInfo($type, $rid, $logic_data, $user_logic)
    {
        // 获取已是最新逻辑的运势时间，用于后面进行比对是否为需要重新计算
        $version_time = [];
        if (in_array($type, [2, 3], true))
        {
            foreach ($user_logic as $value)
            {
                if ($value['version'] == $logic_data['version'])
                {
                    $version_time[] = $value['time'];
                }
            }
        }
        switch ($type)
        {
            case 2:
                $data = (new MonthFortune())
                    ->alias('m')
                    ->join('wechat_backup_07_18_14_43_00.app_fortune_recode_back r', 'm.rid_back=r.id')
                    ->join('wechat_backup_07_18_14_43_00.app_orders o', 'o.order_id=m.order_id')
                    ->field('m.status,m.month time,r.recode_info,m.order_id,m.type,o.order_type,o.env_type,o.id oid')
                    ->where('m.rid', $rid)
                    ->select();
                break;
            case 3:
                $data = (new YearFortune())
                    ->alias('y')
                    ->join('wechat_backup_07_18_14_43_00.app_fortune_recode_back r', 'y.rid_back=r.id')
                    ->join('wechat_backup_07_18_14_43_00.app_orders o', 'o.order_id=y.order_id')
                    ->field('y.status,y.year time,r.recode_info,y.order_id,y.type,o.order_type,o.env_type,o.id oid,y.version')
                    ->where('y.rid', $rid)
                    ->select();
                break;
            default :
                $data = [];
                break;
        }
        $tmp = [];
        foreach ($data as $datum)
        {
            $unlockTime[$datum['order_id']][] = $datum['time'];
            $tmp[$datum['order_id']] = [
                'status' => $datum['status'],
                'time' => $unlockTime[$datum['order_id']],
                'order_type' => $datum['order_type'],
                'env_type' => $datum['env_type'],
                'order_id' => $datum['order_id'],
                'id' => $datum['oid'],
                'type' => $datum['type'],
                'recode_info' => $datum['recode_info'],
                'version' => $datum['version'],
            ];
        }
        foreach ($tmp as $t)
        {
            $recodeInfo = json_decode($t['recode_info'], true);
            $recodeInfo['uid'] = $this->user['id'];
            $t['order_type'] = $type + 1;
            $t['env_type'] = 0;

            if (empty($t['version']) || Util::CheckAppVersion('2.10.1', $t['version']) === '小')
            {
                $version_time = array_values(array_diff($version_time, $t['time']));
            }
            $diffTime = array_diff($t['time'], $version_time);
            $version = $this->headers['version'] ?? '';
            if ($diffTime)
            {
                (new PushQueue())->fortune_queue($t, [$recodeInfo], $diffTime, $t['type'], $version);

                foreach ($diffTime as $time)
                {
                    switch ($type)
                    {
                        case 2:
                            (new MonthFortune())->where(['order_id' => $t['order_id']])->update(['status' => 1]);
                            // 月运缓存删除
                            CacheManage::getInstance()->setCacheConfig('fortune.fortune_month')
                                ->setCacheKeyDetail('details_v2', $rid . ':' . $time)
                                ->rmCache('details_v2');

                            break;
                        case 3:
                            $updateData = [
                                'status' => 1,
                            ];
                            if ($version)
                            {
                                $updateData['version'] = $version;
                            }
                            (new YearFortune())->where(['order_id' => $t['order_id']])->update($updateData);
                            // 年运缓存删除
                            CacheManage::getInstance()->setCacheConfig('fortune.fortune_year')
                                ->setCacheKeyDetail('details_v2', $rid . ':' . $time)
                                ->rmCache('details_v2');
                            break;
                    }
                }
            }
        }
    }
}
